package net.kazed.nextaction.database;

import java.util.Map;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;

public abstract class QueryTemplate {

    private SQLiteDatabase db;

    /**
     * Constructor.
     * @param db Database.
     */
    public QueryTemplate(SQLiteDatabase db) {
        super();
        this.db = db;
    }
    
    public Task queryFirst(String tableName, Map<String, String> projectionMap, String[] selectColumns) {
        Task task = null;
        SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
        qb.setTables(tableName);
        qb.setProjectionMap(projectionMap);
        Cursor cursor = null;
        try {
            cursor = qb.query(db, selectColumns, null, null, null, null, null);
            if (cursor.moveToFirst()) {
                task = mapRow(cursor);
            }
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
        
        return task;
    }
    
    /**
     * Map row to object.
     * @param cursor Query cursor.
     * @return Mapped object.
     */
    abstract public Task mapRow(Cursor cursor);

}
